<template>
  <div class="table-all">
    <!-- 搜索区 -->
    <div class="app-container search-box">
      <SearchForm
        :form="searchData.form"
        :options="searchData.options"
        @searchUpdate="search"
        @resetSearchData="resetSearchData"
      ></SearchForm>
    </div>
    <!-- 按钮区 -->
    <div class="app-container table-box">
      <div class="table-main">
        <!-- 表格 -->
        <v-table
          title="地下空洞隐患预警信息"
          v-if="tableMainHeight>0"
          :table-columns="tableColumns"
          :table-data="tableData"
          :loading="loading"
          :is-index="true"
          ref="table"
          :maxHeight="tableMainHeight">
          <template #topButtonList>
            <ButtonForm :buttonList="buttonList" @clickButton="clickButton"></ButtonForm>
          </template>
          <template #bclassify="scope">
            {{ getDictValue(scope.row.bclassify, bClassifyOptions) }}
          </template>
          <template #sclassify="scope">
            {{ getDictValue(scope.row.sclassify, sClassifyOptions) }}
          </template>
          <template #category="scope">
            {{ getDictValue(scope.row.category, categoryOptions) }}
          </template>
          <template #grade="scope">
            {{ getDictValue(scope.row.grade, gradeOptions) }}
          </template>
          <template #state="scope">
            {{getDictValue(scope.row.state, stateOptions)}}
          </template>
          <template #fromType="scope">
            {{getDictValue(scope.row.fromType, fromTypeOptions)}}
          </template>
          <template #superviseState="scope">
            {{getDictValue(scope.row.superviseState, superviseStateOptions)}}
          </template>

          <template #operation="scope">

            <div v-if="scope.row.state==2||scope.row.state==3" style="text-align: center">
              <a v-hasPermission="['riskHazard:detail']" class="table-btn-view table-operation"
                 @click="detail(scope.row)">{{$t('table.view')}}</a>
            </div>
            <div v-else>
              <a v-hasPermission="['riskHazard:add']" class="table-btn-edit table-operation"
                 @click="handleEdit(scope.row)">{{$t('table.edit')}}</a>

              <a v-hasPermission="['riskHazard:detail']" class="table-btn-view table-operation"
                 @click="detail(scope.row)">{{$t('table.view')}}</a>
              <font v-if="scope.row.superviseOrderNum==null||scope.row.superviseOrderNum==''" >
                <a v-hasPermission="['riskHazard:orderPush']" class="table-btn-view table-operation"
                   @click="supervise(scope.row)">{{$t('table.urge')}}</a>
              </font>
              <a v-hasPermission="['riskHazard:delete']" class="table-btn-delete table-operation"
                 @click="singleDelete(scope.row)">{{$t('table.delete')}}</a>

            </div>

          </template>


        </v-table>
      </div>
      <div class="table-page">
        <!-- 页码 -->
        <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                    @pagination="search"/>
      </div>
    </div>

    <!-- 归档详情 -->
    <detailEndDialog :dialog-visible="detailEndDialogShow"
                     @success="editSuccess"
                     @close="editClose"
                     :openType="detailOpenType"
                     :superviseOrderNum="curSuperviseOrderNum"
                     :id="detailId"
                     :title="detailTitle"
    ></detailEndDialog>

    <!-- 详情 -->
    <detailDialog :dialog-visible="detailDialogShow"
                  @success="editSuccess"
                  @close="editClose"
                  :openType="detailOpenType"
                  :id="detailId"
                  :title="detailTitle"
    ></detailDialog>
  </div>
</template>

<script>
  import {
    riskHazardPage,
    riskHazardExport,
    riskHazardDelete,orderPush
  } from '@/api/risk/riskHazard'
  import SearchForm from '@/components/searchForm/index'
  import ButtonForm from '@/components/ButtonForm/index'
  import VTable from '@/components/VTable/index'
  import Pagination from '@/components/Pagination/index'
  import detailDialog from './detail.vue'
  import detailEndDialog from './detailEnd.vue'

  export default {
    components: {
      VTable, Pagination, detailDialog, SearchForm, ButtonForm,detailEndDialog
    },
    data() {
      return {
        tableColumns: [
          // {
          //   prop: 'flagCode',
          //   label: '标识码',
          //   minWidth: '100',
          //   slotname: 'flagCode',
          //   options: {}
          // },
          {
            prop: 'name',
            label: '隐患名称',
            minWidth: '150',
            slotname: 'name',
            options: {}
          },
          /**
           {
          prop: 'bclassify',
          label: '风险隐患大类',
          minWidth: '150',
          slotname: 'bclassify',
          options: {}
        },
           {
          prop: 'sclassify',
          label: '风险隐患细类',
          minWidth: '150',
          slotname: 'sclassify',
          options: {}
        },
           */

          {
            prop: 'state',
            label: '隐患状态',
            minWidth: '150',
            slotname: 'state',
            options: {}
          },
          {
            prop: 'grade',
            label: '隐患等级',
            minWidth: '150',
            slotname: 'grade',
            options: {}
          },
          {
            prop: 'fromType',
            label: '隐患来源',
            minWidth: '150',
            slotname: 'fromType',
            options: {}
          },

          {
            prop: 'discoveryTime',
            label: '发现时间',
            minWidth: '150',
            slotname: 'discoveryTime',
            options: {}
          },

          {
            prop: 'address',
            label: '隐患地址',
            minWidth: '150',
            slotname: 'address',
            options: {}
          },


          {
            prop: 'finishTimeState',
            label: '是否按时处置',
            minWidth: '150',
            slotname: 'finishTimeState',
            options: {}
          },



          {
            prop: 'reportName',
            label: '上报人',
            minWidth: '150',
            slotname: 'reportName',
            options: {}
          },
          {
            prop: 'reportTime',
            label: '上报时间',
            minWidth: '150',
            slotname: 'reportTime',
            options: {}
          },
          {
            prop: 'superviseState',
            label: '督办状态',
            minWidth: '100',
            slotname: 'superviseState',
            options: {}
          },
          {
            prop: 'operation',
            label: '操作',
            width: '200',
            align: 'center',
            slotname: 'operation',
            overflow: false,
            fixed: 'right'
          }
        ],
        tableData: [],
        selection: [],
        loading: false,
        total: 1,
        pageNum: 1,
        pageSize: 10,
        detailOpenType: "add",
        detailDialogShow: false,
        detailEndDialogShow:false,
        curSuperviseOrderNum:"",
        detailId: "",
        detailTitle: "新增",
        dict: {},
        searchData: {
          form: {
            name: '',
            bclassify: '03',
            address: '',
            state: '',
          },
          options: [
            {
              title: '隐患名称',
              key: "name",
              type: "text",
            },

            {
              title: '隐患地址',
              key: "address",
              type: "text",
            },

            {
              title:'隐患状态',
              key: "state",
              type: "select",
              multiple:false,
              option: {
                data: this.stateOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title:'是否按时处置',
              key: "finishTimeState",
              type: "select",
              multiple:false,
              option: {
                data: this.finishTimeStateOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },


          ]
        },
        buttonList: [
          {name: '新增', methods: 'handleAdd', type: 'primary', hasPremission:["riskHazard:add"]},
          //{name: '导入', methods: 'handleImport'},
          //{name: '导出', methods: 'handleExport'}
        ],
        tableMainHeight: 0,
        // 字典
        bClassifyOptions: [],
        bSlassifyOptions: [],
        categoryOptions: [],
        gradeOptions: [],
        finishTimeStateOptions:[],
        stateOptions:[],
        fromTypeOptions:[],
        superviseStateOptions:[],
      }
    },
    watch: {
      // 字典

      'stateOptions':{
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t=>{
            if(t.key=='state'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },

      'fromTypeOptions':{
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t=>{
            if(t.key=='fromType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },

      'bClassifyOptions': {
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t => {
            if (t.key == 'bclassify') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },

      'sClassifyOptions': {
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t => {
            if (t.key == 'sclassify') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },

      'categoryOptions': {
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t => {
            if (t.key == 'category') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },

      'gradeOptions': {
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t => {
            if (t.key == 'grade') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'finishTimeStateOptions':{
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t=>{
            if(t.key=='finishTimeState'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
    },
    methods: {

      supervise(row){
        this.$confirm('确定督办？', this.$t('common.tips'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
          this.loading = true
          var param = {};
          param.orderNum = row.id;
          var backData ={};
          backData.type='1';
          param.backData = JSON.stringify(backData);
          orderPush(param).then(res=>{
            if(res.code==200){
              this.$message({
                message: '督办提交成功',
                type: 'success'
              })
              this.search()
            }else{
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          }).finally(final=>{
            this.loading = false
          })
        })
      },

      //跳转到详情页
      detail(row){
        this.curSuperviseOrderNum= row.superviseOrderNum
        this.detailEndDialogShow=true;
        this.detailId = row.id;
        this.detailTitle = "详情";
        this.detailOpenType="detail";
      },

      getCheckBoxValue(value, option) {
        if (!value) {
          return
        }
        let temp = []
        let data = value.split(",")
        data.forEach(t => {
          let item = option.find(x => x.value == t)
          if (item != undefined) {
            temp.push(item.label)
          }
        })
        return temp.join(",")
      },
      getDictValue(value, option) {
        let item = option.find(t => t.value == value)
        if (item != undefined) {
          return item.label
        }
        return value
      },
      editClose(){
        this.detailDialogShow = false
        this.detailEndDialogShow = false
      },
      editSuccess(){
        this.search()
        this.detailDialogShow = false
        this.detailEndDialogShow = false
      },
      search() {
        this.fetch({
          ...this.searchData.form,
        })
      },
      fetch(params = {}) {
        params.pageSize = this.pageSize
        params.pageNum = this.pageNum
        params.bclassify = '03'
        params.sclassify = '008'
        params.areaCode = this.$store.state.account.user.deptIds
        //4 代表上报
        params.fromType = '4'
        this.loading = true
        riskHazardPage(params).then(res => {
          if (res.code == 200) {
            this.total = res.data.total
            this.tableData = res.data.rows
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        }).finally(final => {
          this.loading = false
        })
      },
      // 重置搜索条件
      resetSearchData() {
        this.searchData.form = {
          name: '',
          bclassify: '03',
          address: '',
          state: '',
          finishTimeState:''
        }
      },

      // 触发按钮区域按钮方法
      clickButton(methods) {
        this[methods]()
      },
      handleAdd() {
        this.detailOpenType = "add"
        this.detailTitle = "新增"
        this.detailDialogShow = true
      },
      handleEdit(row) {
        this.detailId = row.id
        this.detailOpenType = "edit"
        this.detailTitle = "编辑"
        this.detailDialogShow = true
      },
      handleExport() {
        let params = {
          ...this.searchData.form
        }
        riskHazardExport(params, `风险隐患上报_${new Date().getTime()}.xlsx`);
      },
      handleImport() {
        console.log("等待处理")
      },


      closeDialog() {
        this.detailDialogShow = false
      },

      singleDelete(row) {
        this.$confirm(this.$t('tips.confirmDelete'), this.$t('common.tips'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
          this.loading = true
          riskHazardDelete(row.id).then(res => {
            if (res.code == 200) {
              this.$message({
                message: this.$t('tips.deleteSuccess'),
                type: 'success'
              })
              this.search()
            } else {
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          }).finally(final => {
            this.loading = false
          })
        })
      }
    },
    activated() {
      this.fetch()
    },
    created() {
      this.fetch()
      // 获取字典值
      this.bClassifyOptions = []
      this.$commonJs.filterDataDict("hazardBClassify", this.bClassifyOptions)

      this.sClassifyOptions = []
      this.$commonJs.filterDataDict("hazardSClassify", this.sClassifyOptions)

      this.categoryOptions = []
      this.$commonJs.filterDataDict("hazardCategory", this.categoryOptions)

      this.gradeOptions = []
      this.$commonJs.filterDataDict("patrolHazardLevel", this.gradeOptions)



      this.stateOptions = []
      this.$commonJs.filterDataDict("hazardDealState", this.stateOptions)

      this.fromTypeOptions = []
      this.$commonJs.filterDataDict("hazardFromType", this.fromTypeOptions)

      this.finishTimeStateOptions = [{"name":"1","label":"按时"},{"name":"2","label":"超时"}]

      this.superviseStateOptions = []
      this.$commonJs.filterDataDict("superviseState",this.superviseStateOptions )
    },
    mounted() {
      this.tableMainHeight = document.getElementsByClassName('table-main')[0].clientHeight - 44 //减去顶部按钮列表的高度
    }
  }
</script>

<style lang="scss" scoped>
  .table-all {
    display: flex;
    flex-direction: column;
    height: 100%;

    .search-box {
      padding-bottom: 6px;
    }

    .table-box {
      padding-top: 10px;
      flex: 1;
      display: flex;
      flex-direction: column;

      .table-main {
        flex: 1;
        overflow: auto;
      }

      .table-page {
        // padding-top: 10 px;
        // padding-bottom: 10 px;
      }

      ::v-deep .pagination-container {
        text-align: right;
      }

    }
  }
</style>
